﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using DocTes.Users;
using System.Web.Security;

namespace DocTes.Administration.Users.Controls
{
    public partial class MultipleUser : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ButtonCargar_Click(object sender, EventArgs e)
        {
            if (FileUploadUsers.HasFile)
            {
                if (ChecarExtension(FileUploadUsers.FileName))
                {

                    Label1.Text = FileUploadUsers.FileName + " cargado exitosamente";

                    lblOculto.Text = FileUploadUsers.FileName;


                    MemoryStream ms = new MemoryStream(FileUploadUsers.FileBytes);

                    try
                    {

                        CargarDatos(ms);
                    }
                    catch
                    {
                        Label1.Text = "Error al subir el archivo formato incorrecto .CSV";
                    }

                }

                else
                {
                    Label1.Text = "El archivo no es el tipo .CSV";
                }

            }
            else
            {
                Label1.Text = "Error al subir el archivo o no es el tipo .CSV";
            }

        }




        private UserDto AgregarFila(String fila, int longitud)
        {
            String[] valores = fila.Split(new char[] { ';' });
            Int32 numeroTotalValores = valores.Length;
            if (numeroTotalValores != longitud)
            {
                throw new Exception("Formato invalido");
            }


            UserDto user = new UserDto()
            {
                UserName = valores[0].Trim(),
                Email = valores[1].Trim(),

            };

            return user;
        }


        private void CargarDatos(Stream strm)
        {
            StreamReader lector = new StreamReader(strm);
            String fila = String.Empty;
            Int32 cantidad = 0;
            List<UserDto> users = new List<UserDto>();
            do
            {
                fila = lector.ReadLine();
                if (fila == null)
                {
                    break;
                }
                if (0 != cantidad++)
                {

                    users.Add(this.AgregarFila(fila, 2));
                }
            } while (true);
            DataSourceUsers = users;
            GridView1.DataSource = DataSourceUsers;
            GridView1.DataBind();
        }

        bool ChecarExtension(string fileName)
        {
            string ext = Path.GetExtension(fileName);
            switch (ext.ToLower())
            {
                case ".csv":
                    return true;
                default:
                    return false;
            }
        }


        public List<UserDto> DataSourceUsers
        {
            get
            {
                List<UserDto> users = (ViewState["DataSourceUsuarios"] != null) ? ViewState["DataSourceUsuarios"] as List<UserDto> : new List<UserDto>();
                return users;
            }
            set
            {
                ViewState["DataSourceUsuarios"] = value;
            }
        }

        protected void ButtonCrear_Click(object sender, EventArgs e)
        {
            List<UserDto> users = DataSourceUsers;
            if (users.Count > 0)
            {
               List<KeyValuePair<MembershipUser,MembershipCreateStatus>> result =   DataSourceMembershipUser.CreateUsers(users, TextBoxPassword1.Text);
               List<UserDto> usersResult = new List<UserDto>();
                foreach (KeyValuePair<MembershipUser, MembershipCreateStatus> pair in result)
               {
                   UserDto user = new UserDto()
                   {
                       UserName = pair.Key.UserName,
                       Email = pair.Key.Email,
                       Result =  Enum.GetName(typeof(MembershipCreateStatus),  pair.Value),
                   };
                   usersResult.Add(user);

               }
                GridView2.DataSource = usersResult;
                GridView2.DataBind();

            }
            else
            {
                LabelCrear.Text = "Debe seleccionar primero un archivo";
            }

        }



    }
}